package com.weixin.pay.config;


import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author jacklin
 */
@Configuration
@EnableConfigurationProperties(WxPayProperties.class)
@ConditionalOnClass(WxPayService.class)
@AllArgsConstructor
public class WxPayConfiguration {

    private WxPayProperties wxPayProperties;

    /**
     * 为 WxPayService实例注入配置
     * @return WxPayService
     */
    @Bean
    @ConditionalOnMissingBean
    public WxPayService wxPayService(){
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId(wxPayProperties.getAppId());
        wxPayConfig.setMchId(wxPayProperties.getMchId());
        wxPayConfig.setMchKey(wxPayProperties.getMchKey());
        wxPayConfig.setKeyPath(wxPayProperties.getKeyPath());
        wxPayConfig.setSubAppId(StringUtils.trimToNull(wxPayProperties.getSubAppId()));
        wxPayConfig.setSubMchId(StringUtils.trimToNull(wxPayProperties.getSubMchId()));

        // 可以指定是否使用沙箱环境
        wxPayConfig.setUseSandboxEnv(false);
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(wxPayConfig);
        return wxPayService;
    }

}
